<template>
  <div class="welcom">
    <el-card>
      <el-row :gutter="10">
        <el-col :span="8">
          <p>总阅读量</p>
          <div>
            <strong style="font-size: 28px; padding-right: 10px">{{ statistic.viewCount }}</strong>
            <el-icon :size="20">
              <i-ep-User />
            </el-icon>
          </div>
        </el-col>
        <el-col :span="8">
          <p>总点赞量</p>
          <div>
            <strong style="font-size: 28px; padding-right: 10px">{{ statistic.voteCount }}</strong>
            <SvgIcon name="good"></SvgIcon>
          </div>
        </el-col>
        <el-col :span="8">
          <p>点赞率</p>
          <div>
            <strong style="font-size: 28px; padding-right: 10px; color: #f56c6c"
              >{{ votePercent() }}%</strong
            >
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <el-card>
          <el-row :gutter="10">
            <el-col :span="12">
              <p>今日阅读</p>
              <div>
                <strong style="font-size: 28px; padding-right: 10px">{{
                  statistic.viewIncrease
                }}</strong>
                <el-icon :size="20">
                  <i-ep-User />
                </el-icon>
              </div>
            </el-col>
            <el-col :span="12">
              <p>今日点赞</p>
              <div>
                <strong style="font-size: 28px; padding-right: 10px">{{
                  statistic.voteIncrease
                }}</strong>
                <SvgIcon name="good"></SvgIcon>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <el-row :gutter="10">
            <el-col :span="12">
              <p>预计今日阅读</p>
              <div>
                <strong style="font-size: 28px; padding-right: 10px; color: #409eff">{{
                  statistic.todayViewIncrease
                }}</strong>
                <el-icon :size="20">
                  <i-ep-User />
                </el-icon>
              </div>
            </el-col>
            <el-col :span="12">
              <p>预计今日阅读增长</p>
              <div>
                <el-icon v-if="statistic.todayViewIncreaseRate > 0" :size="28" color="#f56c6c">
                  <i-ep-top />
                </el-icon>
                <el-icon v-else :size="28" color="#67c23a">
                  <i-ep-bottom />
                </el-icon>
                <strong
                  :style="{
                    fontSize: '28px',
                    paddingRight: '10px',
                    color: statistic.todayViewIncreaseRate > 0 ? '#f56c6c' : '#67c23a'
                  }"
                  >{{ statistic.todayViewIncreaseRateAbs }}%</strong
                >
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <el-card class="echart-card">
      <div id="echart-box"></div>
    </el-card>
  </div>
</template>

<script setup>
import { getStatistic, getMonthStatistic } from '@/api/ebookSnapshot'
import SvgIcon from '@/components/svgIcon/SvgIcon.vue'
import * as echarts from 'echarts'
import { onUnmounted } from 'vue'

const statisticResp = ref()
const statistic = ref({})
const monthStatisticResp = ref()
let myChart = null
// 日期
const xAxisData = []
// 阅读量
const series1Data = []
// 点赞量
const series2Data = []
const echartOption = {
  title: {
    text: '近30天趋势'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['阅读量', '点赞量']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '阅读量',
      type: 'line',
      stack: 'Total',
      smooth: true,
      data: []
    },
    {
      name: '点赞量',
      type: 'line',
      stack: 'Total',
      smooth: true,
      data: []
    }
  ]
}

onMounted(() => {
  queryStatistic()
  queryMonthStatistic()
  initEchart()
  // 屏幕发生变化时更新图表
  window.onresize = function () {
    if (!myChart) return
    myChart.resize()
  }
})

onActivated(() => {
  queryStatistic()
  queryMonthStatistic()
  initEchart()
  // 屏幕发生变化时更新图表
  window.onresize = function () {
    if (!myChart) return
    myChart.resize()
  }
})

onUnmounted(() => {
  window.onresize = null
  if (!myChart) return
  // 销毁图标
  myChart.dispose()
})

onDeactivated(() => {
  window.onresize = null
  if (!myChart) return
  // 销毁图标
  myChart.dispose()
})

const initEchart = () => {
  // 基于准备好的dom，初始化echarts实例
  myChart = echarts.init(document.getElementById('echart-box'))
  myChart.setOption(echartOption)
}

const updateEchart = () => {
  /**
	 * 通过传递新的option参数来更新图表，但注意：使用该方法必须手动设置notMerge参数为false，否则会替换掉整个图表，导致图表的其他设置被重置。
			myChart.setOption({
					series: {
							data: [10, 20, 30, 40, 50, 60]
					}
			}, false);
	 */
  myChart.setOption(
    {
      xAxis: {
        data: xAxisData
      },
      series: [
        {
          data: series1Data
        },
        {
          data: series2Data
        }
      ]
    },
    false
  )
}

const votePercent = () => {
  if (!statistic.value.viewCount) return 0
  const percent = ((statistic.value.voteCount / statistic.value.viewCount) * 100).toFixed(2)
  return percent
}

const queryMonthStatistic = async () => {
  const { success, data, message } = await getMonthStatistic()
  if (success) {
    monthStatisticResp.value = data
    data.forEach((item) => {
      xAxisData.push(item.date)
      series1Data.push(item.viewIncrease)
      series2Data.push(item.voteIncrease)
    })
    nextTick(() => {
      updateEchart()
    })
  } else {
    ElMessage({
      type: 'error',
      message
    })
  }
}

const queryStatistic = async () => {
  const { success, data, message } = await getStatistic()
  if (success) {
    statisticResp.value = data
    // 按分钟计算当前时间点，占一天的百分比
    const now = new Date()
    const nowRate = (now.getHours() * 60 + now.getMinutes()) / (60 * 24)
    // 当有两条数据时，0 为 昨天的数， 1 为今天的数据
    if (data.length > 1) {
      statistic.value.viewCount = data[1].viewCount // 总阅读数
      statistic.value.voteCount = data[1].voteCount // 总点赞数
      statistic.value.viewIncrease = data[1].viewIncrease // 今日阅读数
      statistic.value.voteIncrease = data[1].voteIncrease // 今日点赞数
      // 预计今日阅读
      statistic.value.todayViewIncrease = (data[1].viewIncrease / nowRate).toFixed(0)
      // 预计今日增长率
      if (data[0].viewIncrease) {
        statistic.value.todayViewIncreaseRate = (
          ((statistic.value.todayViewIncrease - data[0].viewIncrease) / data[0].viewIncrease) *
          100
        ).toFixed(2)
      } else {
        statistic.value.todayViewIncreaseRate = statistic.value.todayViewIncrease * 100
      }
      // 预计今日增长率绝对值
      statistic.value.todayViewIncreaseRateAbs = Math.abs(statistic.value.todayViewIncreaseRate)
    } else {
      // 只有今天的数据
      statistic.value.viewCount = data[0].viewCount // 总阅读数
      statistic.value.voteCount = data[0].voteCount // 总点赞数
      statistic.value.viewIncrease = data[0].viewIncrease // 今日阅读数
      statistic.value.voteIncrease = data[0].voteIncrease // 今日点赞数

      // 预计今日阅读
      statistic.value.todayViewIncrease = (data[0].viewIncrease / nowRate).toFixed(0)
      // 预计今日增长率
      statistic.value.todayViewIncreaseRate = statistic.value.todayViewIncrease * 100
      // 预计今日增长率绝对值
      statistic.value.todayViewIncreaseRateAbs = Math.abs(statistic.value.todayViewIncreaseRate)
    }
  } else {
    ElMessage({
      type: 'error',
      message
    })
  }
}
</script>

<style lang="scss" scoped>
.welcom {
  height: 100%;
  display: flex;
  flex-direction: column;
  :deep(.echart-card) {
    margin-top: 20px;
    flex: 1;
    .el-card__body {
      box-sizing: border-box;
      height: 100%;
    }
    #echart-box {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
